﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using CustomerEmailer.Common;
using System.Collections;
using System.Xml.Linq;
using Microsoft.SqlServer.Server;
using System.Xml;
using System.Threading;
using System.Net.Mail;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;

namespace CustomerEmailer
{
    public partial class Contacts : Form
    {
        public const int WM_NCLBUTTONDOWN = 0xA1;
        public const int HT_CAPTION = 0x2;

        [DllImportAttribute("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd,
                         int Msg, int wParam, int lParam);
        [DllImportAttribute("user32.dll")]
        public static extern bool ReleaseCapture();
        TreeNode CurrentNode { get; set; }
        private bool IsEditCustomers { get; set; }
        Main mainClass;

        public Contacts(Main main1)
        {
            InitializeComponent();
            mainClass = main1;
        }

        bool ignoreSelected=false;
        
        private void Contacts_Load(object sender, EventArgs e)
        {
            Utils.updatingContacts = true;
            contactsTreeView.InitalizeTreeNode(Main.XML_FILE_LOCATION);
            contactsTreeView.treeView1.CheckBoxes = false;
            contactsTreeView.treeView1.AllowDrop = true;
            contactsTreeView.treeView1.CollapseAll();
            contactsTreeView.treeView1.Size = new Size(394, 483);
            contactsTreeView.treeView1.AfterSelect += new TreeViewEventHandler(treeView1_AfterSelect);
            if (mainClass.contactsTreeView.selectedTreeView.SelectedNode != null)
                if (mainClass.contactsTreeView.selectedTreeView.SelectedNode.ImageKey == "Customers")
                    Utils.FindNodeInHierarchyByPath(contactsTreeView.treeView1.Nodes, mainClass.contactsTreeView.selectedTreeView.SelectedNode.Nodes[0].FullPath, contactsTreeView.treeView1);
        }

        void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (!ignoreSelected)
            {
                btnNewCustomer_Click(null, null);
                TreeNode node = contactsTreeView.treeView1.SelectedNode;
                CurrentNode = node;
                if (node.ImageKey == "ContactGrp")
                {
                    pnlEditContactGrp.Visible = true;
                    pnlEditCustomer.Visible = false;
                    IsEditCustomers = false;
                    rbGroup.Checked = true;
                    btnUpdateContactGrp.Enabled = true;
                    btnAddContactGrp.Enabled = false;
                    btnDeleteContactGrp.Enabled = true;
                    PopulatePnlEditContactGrp(node.Text);
                    lvGroups.Clear();
                }
                else if (node.ImageKey == "Customers")
                {
                    pnlEditCustomer.Visible = true;
                    pnlEditContactGrp.Visible = false;
                    IsEditCustomers = true;
                    rbCustomer.Checked = true;
                    btnUpdateCustomer.Enabled = true;
                    btnAddCustomer.Enabled = false;
                    btnDeleteCustomer.Enabled = true;
                    PopulatePnlEditCustomer(node.Text, node.Name, node.ToolTipText, node.Parent, (string)node.Tag);
                    List<TreeNode> nodes_list = new List<TreeNode>();
                    Utils.getEquivalentNodes(contactsTreeView.treeView1.Nodes, ref nodes_list, CurrentNode);
                    lvGroups.Clear();
                    lvAllGroups.Clear();
                    addAllGroup();
                    foreach (TreeNode enode in nodes_list)
                    {
                        lvGroups.Items.Add(enode.Parent.Text, enode.Parent.FullPath);
                    }
                    if (node.Nodes.Count == 2)
                        PopulatePnlEditEmail(node.Nodes[0].Text, node.Nodes[1].Text);
                    else //has to be 1 email minimum
                        PopulatePnlEditEmail(node.Nodes[0].Text, "");
                }
            }
        }

        private void PopulatePnlEditContactGrp(string name)
        {
            tbContactGrp.Text = name.Replace("''", "\"");
        }

        private void PopulatePnlEditCustomer(string name,string fname,string de, TreeNode group, string phones)
        {
            tbCustomerFName.Text = fname;
            try
            {
                tbCustomerLName.Text = name.Substring(fname.Length+1);
            }
            catch (Exception e) { }
            tbDetail.Text = de.Replace("''", "\"");
            String[] array1 = phones.Split('#');                
           /* if (array1.GetLength(0) == 1)
                txtMobile.Text=array1[0];
            if (array1.GetLength(0) == 2)
            {*/
            if (array1.Length>0)
                txtMobile.Text = array1[0];
            if (array1.Length >= 1)
                txtOffice.Text = array1[1];
            if (array1.Length >= 2)
                tbAddress.Text = array1[2];

            //}
        }

        private void PopulatePnlEditEmail(string email1,string email2)
        {
            tbMail1.Text = email1;
            tbMail2.Text = email2;
        }

        private void btnAddCustomer_Click(object sender, EventArgs e)
        {
            ignoreSelected = true;
            if (!(ValidateCustomer(tbMail1.Text) && (ValidateCustomer(tbMail2.Text) || tbMail2.Text == "")))
            {
                MessageBox.Show("כתובות אימייל שהוכנסו אינן תקינות");
                return;
            }
            var customerName = tbCustomerFName.Text.Replace("\"", "''") +" "+ tbCustomerLName.Text.Replace("\"", "''");
            var extraInfo = tbDetail.Text.Replace("\"", "''");
                TreeNode node = new TreeNode();
                node.Text = customerName;
                node.Name = tbCustomerFName.Text.Replace("\"", "''");
                if (ValidateCustomer(tbMail1.Text))
                {
                    TreeNode emailNode = new TreeNode();
                    emailNode.Text = tbMail1.Text;
                    emailNode.ImageKey = "Email";
                    node.Nodes.Add(emailNode);
                }
                if (ValidateCustomer(tbMail2.Text))
                {
                    TreeNode emailNode = new TreeNode();
                    emailNode.Text = tbMail2.Text;
                    emailNode.ImageKey = "Email";
                    node.Nodes.Add(emailNode);
                }
                node.ToolTipText = extraInfo;
                node.Tag = txtMobile.Text + "#" + txtOffice.Text + "#"+ tbAddress.Text;
                
                node.ImageKey = "Customers";

                TreeNode parent=null;
                for (int i = 0; i < lvGroups.Items.Count; i++)
                {
                    Utils.SilentlyFindNodeInHierarchyByPath(contactsTreeView.treeView1.Nodes, lvGroups.Items[i].ImageKey,ref parent,"ContactGrp");
                    parent.Nodes.Add((TreeNode)node.Clone());
                }

                btnNewCustomer_Click(null, null);
             //   contactsTreeView.sort(contactsTreeView.selectedTreeView.Nodes[0]); if they request
                ignoreSelected = false;
        }

        private void btnAddContactGrp_Click(object sender, EventArgs e)
        {
            if (!ValidateContactGroup())
            {
                return;
            }
            if (CurrentNode.ImageKey!="ContactGrp")
            {
                ShowErrorMessage("לא ניתן להוסיף קבוצה למשתמש. רק להיפך.", "שגיאה ביצירת קבוצה");
                return;
            }

            TreeNode node = new TreeNode();
            node.Text = tbContactGrp.Text.Replace("\"", "''");
            node.ImageKey = "ContactGrp";

            if (node == null)
            {
                contactsTreeView.treeView1.Nodes.Add(node);
                CurrentNode = node;
            }
            else
            {
                CurrentNode.Nodes.Add(node);
            }
        }

        private void btnUpdateCustomer_Click(object sender, EventArgs e)
        {
            ignoreSelected = true;
            if (ValidateCustomer(tbMail1.Text) && (ValidateCustomer(tbMail2.Text) || tbMail2.Text == ""))
            {
                List<TreeNode> node_list = new List<TreeNode>();
                Utils.getEquivalentNodes(contactsTreeView.treeView1.Nodes, ref node_list, CurrentNode);
                foreach (TreeNode node in node_list)
                {
                    node.Remove();
                }
                btnAddCustomer_Click(null, null);
               /* foreach (TreeNode node1 in node_list)
                {
                    node1.Nodes.Clear();
                    if (ValidateCustomer(tbMail1.Text))
                    {
                        TreeNode emailNode = new TreeNode();
                        emailNode.Text = tbMail1.Text;
                        emailNode.ImageKey = "Email";
                        node1.Nodes.Add(emailNode);
                    }
                    if (ValidateCustomer(tbMail2.Text))
                    {
                        TreeNode emailNode = new TreeNode();
                        emailNode.Text = tbMail2.Text;
                        emailNode.ImageKey = "Email";
                        node1.Nodes.Add(emailNode);
                    }
                    node1.Text = tbCustomerFName.Text.Replace("\"", "''") + " " + tbCustomerLName.Text.Replace("\"", "''");
                    node1.Name = tbCustomerFName.Text.Replace("\"", "''");
                    node1.Tag = txtMobile.Text.Replace("\"", "''") + "," + txtOffice.Text.Replace("\"", "''") + "," + tbAddress.Text.Replace("\"", "''");
                    node1.ToolTipText = tbDetail.Text.Replace("\"", "''");
                }*/
            }
            else
                MessageBox.Show("כתובות אימייל שהוכנסו אינן תקינות");
            ignoreSelected = false;
        }

        private void btnUpdateContactGrp_Click(object sender, EventArgs e)
        {
            if (ValidateContactGroup())
            {
                CurrentNode.Text = tbContactGrp.Text.Replace("\"", "''");
            }
        }

        private void btnDeleteCustomer_Click(object sender, EventArgs e)
        {
            List<TreeNode> node_list = new List<TreeNode>();
            Utils.getEquivalentNodes(contactsTreeView.treeView1.Nodes, ref node_list, CurrentNode);
            foreach (TreeNode node in node_list)
            {
                node.Remove();
            }
            btnNewCustomer_Click(null, null);
        }

        private void btnDeleteContactGrp_Click(object sender, EventArgs e)
        {
            string input = Microsoft.VisualBasic.Interaction.InputBox("הכנס סיסמא בכדי למחוק", "", "", Screen.PrimaryScreen.Bounds.Width / 3, Screen.PrimaryScreen.Bounds.Height / 3);
            if (input == Properties.Settings.Default.GroupDeletePassword)
                DeleteCurrentNode();
            else
                Microsoft.VisualBasic.Interaction.MsgBox("הסיסמא שגויה");
        }

        void DeleteCurrentNode()
        {
            if (CurrentNode.Level != 0)
            {
                CurrentNode.Remove();
            }
            else
            {
                ShowErrorMessage("לא ניתן להסיר את קבוצת אנשי הקשר הראשית",
                                 "שגיאה במחיקת הנתונים");
            }
        }

        private void btnNewCustomer_Click(object sender, EventArgs e)
        {
            //rbCustomer.Checked = true;
           // rbCustomer_CheckedChanged(null, null);
            tbContactGrp.Clear();
            tbCustomerFName.Clear();
            tbCustomerLName.Clear();
            tbDetail.Clear();
            tbMail1.Clear();
            tbMail2.Clear();
            txtMobile.Clear();
            txtOffice.Clear();
            tbAddress.Clear();
            lvGroups.Clear();
            lvAllGroups.Clear();
            //lbContactGrp.SelectionMode = SelectionMode.MultiSimple;
            //lbContactGrp.Enabled = true;
        }

        private void btnNewContactGrp_Click(object sender, EventArgs e)
        {
           // rbGroup.Checked = true;
            //rbGroup_CheckedChanged(null, null);
            tbContactGrp.Clear();
            btnNewCustomer_Click(null, null);
        }

        private void rbGroup_CheckedChanged(object sender, EventArgs e)
        {
            if (rbGroup.Checked)
            {
                pnlEditContactGrp.Visible = true;
                pnlEditCustomer.Visible = false;
                btnAddContactGrp.Enabled = true;
                btnUpdateContactGrp.Enabled = false;
                btnDeleteContactGrp.Enabled = false;

                tbContactGrp.Text = string.Empty;

                btnNewCustomer_Click(null, null);
            }
        }

        private void rbCustomer_CheckedChanged(object sender, EventArgs e)
        {
            if (rbCustomer.Checked)
            {
                pnlEditContactGrp.Visible = false;
                pnlEditCustomer.Visible = true;
                var treeNodes = contactsTreeView.GetGroupNodes();
                //removing the first most node
                treeNodes.RemoveAt(treeNodes.Count - 1);
                tbContactGrp.Text = string.Empty;

                btnUpdateCustomer.Enabled = false;
                btnAddCustomer.Enabled = true;
                btnDeleteCustomer.Enabled = false;

                btnNewCustomer_Click(null, null);

                addAllGroup();
            }
        }

        void addAllGroup()
        {
            foreach (TreeNode node in contactsTreeView.selectedTreeView.Nodes[0].Nodes)
            {
                lvAllGroups.Items.Add(node.Text, node.FullPath);
            }
        }

        bool ValidateContactGroup()
        {
            if (tbContactGrp.Text == string.Empty)
            {
                ShowErrorMessage("שם הקבוצה שהזנת אינה תקינה",
                               "שגיאה בנתונים שהזנת");
                return false;
            }
            return true;
        }

        bool ValidateCustomer(string Email)
        {
           /* if (lbContactGrp.Items.Count == 0)
            {
                ShowErrorMessage("עליך לבחור קבוצת אנשי קשר לשייך אליה את הלקוח",
                                "שגיאה בנתונים שהזנת");
                return false;
            }
            */
            if (tbCustomerFName.Text == string.Empty && !Utils.IsEmail(Email))
            {
             //   ShowErrorMessage("כתובת המייל ושם הלקוח שהזנת אינם תקינים",
               //                 "שגיאה בנתונים שהזנת");
                return false;
            }
            else if (tbCustomerFName.Text == string.Empty && Utils.IsEmail(Email))
            {
            //    ShowErrorMessage("שם הלקוח שהזנת אינו תקין",
             //                   "שגיאה בנתונים שהזנת");
                return false;
            }
            else if (tbCustomerFName.Text != string.Empty && !Utils.IsEmail(Email))
            {
               // ShowErrorMessage("כתובת המייל שהזנת אינה תקינה",
                 //               "שגיאה בנתונים שהזנת");
                return false;
            }
            return true;
        }

        void ShowErrorMessage(string title, string content)
        {
            MessageBox.Show(title,
                            content,
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error,
                            MessageBoxDefaultButton.Button1,
                            MessageBoxOptions.RightAlign);
        }


        private void btnSave_Click(object sender, EventArgs e)
        {
            var userRslt = MessageBox.Show("האם אתה בטוח שברצונך לשמור שינויים אלו?",
                                            "שים לב, השינויים הבאים ישמרו",
                                            MessageBoxButtons.YesNo,
                                            MessageBoxIcon.Warning,
                                            MessageBoxDefaultButton.Button1,
                                            MessageBoxOptions.RightAlign);
            switch (userRslt)
            {
                case DialogResult.No:
                    break;
                case DialogResult.Yes:
                    contactsTreeView.ExportToXml(Main.XML_FILE_LOCATION);
                    if (!updateServer())
                        MessageBox.Show("שמירת שינויים לא בוצעה בהצלחה - בעיה בשרת");
                    break;
                default:
                    break;
            }
        }

        private bool updateServer()
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://" + Utils.GetSetting("ServerIP") + ":8080?updateContacts");
            request.Method = "PUT";
            request.ContentType = "text/plain";
            FileStream myFile =File.OpenRead(".\\ApplicationData\\customers.xml");
            request.ContentLength = myFile.Length;
            progressBar1.Maximum = 100;
            Stream dataStream = request.GetRequestStream();               
            byte[] buff = new byte[1024];
            int readbytes = 1;
            long totalreadbytes = 0;
            while (readbytes > 0)
            {
                readbytes = myFile.Read(buff, 0, buff.Length);
                totalreadbytes += readbytes;
                progressBar1.Value =(int) (totalreadbytes * 100 / myFile.Length);
                if (readbytes > 0)
                    dataStream.Write(buff, 0, readbytes);
            }
            myFile.Close();                
            dataStream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string returnString = response.StatusCode.ToString();
            response.Close();
            progressBar1.Value = 100;
            return (returnString == "OK");
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            var userRslt = MessageBox.Show("האם שמרת את הנתונים שרצית?",
                                           "אתה בטוח שברצונך לצאת מהמסך?",
                                           MessageBoxButtons.YesNo,
                                           MessageBoxIcon.Warning,
                                           MessageBoxDefaultButton.Button1,
                                           MessageBoxOptions.RightAlign);
            switch (userRslt)
            {
                case DialogResult.No:
                    break;
                case DialogResult.Yes:
                    this.Close();
                    break;
                default:
                    break;

            }
        }

        private void btnFreeze_Click(object sender, EventArgs e)
        {
            TreeNode selectedNode = CurrentNode;
            List<TreeNode> nodes_list = new List<TreeNode>();
           TreeNode FreezeNode =Utils.getFrozenNode(contactsTreeView.treeView1.Nodes[0].Nodes);
           // TreeNode FreezeNode = nodes_list[0];
            //nodes_list.Clear();
            Utils.getEquivalentNodes(contactsTreeView.treeView1.Nodes, ref nodes_list, selectedNode);
            foreach (TreeNode node in nodes_list)
                node.Remove();
            FreezeNode.Nodes.Add(selectedNode);
        }

        private void Contacts_Paint(object sender, PaintEventArgs e)
        {
            this.Region = new System.Drawing.Region(Utils.drawRoundedRect(0,0,15,this.Height,this.Width));
            Utils.drawBorder(0, 0, 15, this.Height, this.Width, e);
        }

        private void Contacts_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ReleaseCapture();
                SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
            }
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("IExplore", " http://www.socialbiz.co.il");
        }

        private void contactsTreeView_Load(object sender, EventArgs e)
        {

        }

        private void lvGroups_SelectedIndexChanged(object sender, EventArgs e)
        {
           
        }

        private void btnAddGroup_Click(object sender, EventArgs e)
        {
            if (lvAllGroups.SelectedItems.Count > 0)
            {
                for (int i = 0; i < lvAllGroups.SelectedItems.Count; i++)
                {
                    lvGroups.Items.Add((ListViewItem)lvAllGroups.SelectedItems[i].Clone());
                }
            }
        }

        private void btnRemoveGroup_Click(object sender, EventArgs e)
        {
            if (lvGroups.SelectedItems.Count > 0)
            {
                int count = lvGroups.SelectedItems.Count;
                for (int i = 0; i < count; i++)
                {
                    lvGroups.Items.Remove(lvGroups.SelectedItems[0]);
                }
            }
        }

    }
}
